<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/15 16:28
 * Modified Time: 2019/8/15 16:28
 * Version: 2.0
 */

namespace App\Modules\Employee\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class GetEmployeeInfoCriteria extends BaseCriterias
{
    protected $user_id;
    protected $store_id;

    public function __construct($user_id,$store_id)
    {
        $this->user_id = $user_id;
        $this->store_id = $store_id;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $user_id = $this->user_id;
        $store_id = $this->store_id;

        $user_like_query = DB::table('user_like')
            ->selectRaw('count(*) as fans_num,user_id')
            ->where('user_id', $user_id)
            ->groupBy('user_id');


        $select = [
            'nick',
            'hx_picture.image as portrait',
            'DATEDIFF(now(),hx_user_store.created_at) + 1 as days',
            'hx_user_store.created_at',
            'introduction',
            'mobile',
            'wechat',
            'IFNULL(hx_user_like.fans_num,0) as fans_num',
            'IF(profile_picture IS NOT NULL and profile_video IS NOT NULL,1,0) as profile'
        ];
        $select = implode($select, ',');
        return $model->selectRaw($select)
            ->leftJoin('picture', 'user.portrait', 'picture.id')
            ->leftJoin('user_store', 'user.id', 'user_store.uid')
            ->leftJoin(\DB::raw("({$user_like_query->toSql()}) as hx_user_like"), function ($join) use ($user_like_query) {
                $join->mergeBindings($user_like_query)->on('user.id', '=', 'user_like.user_id');
            })
            ->where('user.id', $user_id)
            ->where('user_store.sid', $store_id)
            ->where('user_store.rid', 2);
    }
}